import { login, logout } from "../api/users"
import { USER_LOGIN, USER_LOGOUT } from "./action-types"

/**
 * 用户登录 action
 * @param {*} param0 
 */
export const loginAction = ({username, password, remember}) => dispatch => {
  login({username, password})
    .then(res => {
      console.log('登录：', res)
      dispatch({
        type: USER_LOGIN,
        payload: {
          username: res.username,
          token: res.token,
          isLogin: true
        }
      })
      // 判断是否有记住用户
      if (remember) {
        localStorage.setItem('username', res.username)
        localStorage.setItem('token', res.token)
      } else {
        sessionStorage.setItem('username', res.username)
        sessionStorage.setItem('token', res.token)
      }
    })
    .catch(e => console.log('登录异常：', e))
}

/**
 * 用户退出 action
 * @param {*} username 
 */
export const logoutAction = username => dispatch => {
  logout(username)
    .then(res => {
      console.log(res)
      dispatch({
        type: USER_LOGOUT
      })
      // 将本地 Storage 中存储的数据清除
      localStorage.clear()
      sessionStorage.clear()
    })
    .catch(e => console.log('退出异常：', e))
}
